﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using tfs = Microsoft.TeamFoundation.WorkItemTracking.Client;
using AgileDashboard.Entities;
using AgileDashboard.Data.Converters;
using AutoMapper;


namespace AgileDashboard.Data
{
    public class WorkItemFactory
    {
        public static WorkItem CreateWorkItem(tfs.WorkItem workItem, int level)
        {
            if (workItem.Type.Name == "User Story")
                return ConvertUserStory(workItem, level);
            if(workItem.Type.Name == "Task")
                return ConvertTask(workItem, level);

            return null;
        }






        private static WorkItem ConvertWorkItem(tfs.WorkItem workItem)
        {

            Mapper.CreateMap<tfs.WorkItem, WorkItem>();
            WorkItem myWorkItem = Mapper.Map<tfs.WorkItem, WorkItem>(workItem);

            UpdateOtherWorkItemProperties(workItem, myWorkItem);
            

            return myWorkItem;
        }



        private static UserStory ConvertUserStory(tfs.WorkItem workItem, int level)
        {

            Mapper.CreateMap<tfs.WorkItem, UserStory>();
            UserStory userStory = Mapper.Map<tfs.WorkItem, UserStory>(workItem);


            userStory.WorkItemType = ConvertWorkItemType(workItem.Type);
 
            userStory.StoryPoints = FieldDataSource.GetDoubleFieldValue("Story Points", workItem.Fields);

            UpdateOtherWorkItemProperties(workItem, (WorkItem)userStory);

            return userStory;

        }



        private static Task ConvertTask(tfs.WorkItem workItem, int level)
        {
            Mapper.CreateMap<tfs.WorkItem, Task>();
            Task task = Mapper.Map<tfs.WorkItem, Task>(workItem);
            task.WorkItemType = ConvertWorkItemType(workItem.Type);

            UpdateOtherWorkItemProperties(workItem, (WorkItem)task);

            return task;

        }



        private static WorkItemType ConvertWorkItemType(tfs.WorkItemType workItemType)
        {
            if (workItemType.Name == "User Story")
                return WorkItemType.User_Story;
            if (workItemType.Name == "Task")
                return WorkItemType.Task;
            else
                return WorkItemType.None;


        }

        private static void UpdateOtherWorkItemProperties(tfs.WorkItem workItem, WorkItem myWorkItem)
        {

            myWorkItem.Id = workItem.Id;
            myWorkItem.CreationTimeStamp = DateTime.Now;
            myWorkItem.UpdateTimeStamp = DateTime.Now;


            myWorkItem.CreatedBy = myWorkItem.ChangedBy;
            myWorkItem.UpdatedBy = myWorkItem.ChangedBy;

            if (myWorkItem.ChangedDate == DateTime.MinValue)
            {
                myWorkItem.ChangedDate = DateTime.Now;
            }

        }

    }
}
